package com.io.example.demoparent.queue;

/**
 * 环形队列
 */
class CircleQueue {

    private int maxSize;   //表示数组的最大容量

    private int front;    //队列头

    private int rear;   //队列尾

    private int[] arr;  //改数组用于存储数据

    public CircleQueue(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
        front = 0;
        rear = 0;
    }

    /**
     * 判断队列是否为空
     *
     * @return
     */
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }


    public boolean isEmpty() {
        return rear == front;
    }

    /**
     * 向队列添加数据
     *
     * @param data
     */

    public void addQueue(int data) {
        if (isFull()) {
            System.out.println("队列数据已满---------");
            return;
        }
        arr[rear] = data;
        rear = (rear + 1) % maxSize;
    }

    /**
     * 从队列中获取数据
     *
     * @return
     */

    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列空");
        }
        //todo front是指向队列第一个元素
        //  1.先把front对应的值保存到一个临时变量
        //  2.将front后移
        //  3.将临时保存的变量放回

        int value = arr[front];
        front = (front + 1) % maxSize;

        return value;
    }

    /**
     * 求出当前队列有效数据个数
     *
     * @return
     */
    public int size() {

        return (rear + maxSize - front) % maxSize;
    }

    /**
     * 展示队列所有数据
     */

    public void showQueue() {
        if (this.isEmpty()) {
            System.out.println("当前队列数据为空");
        } else {
            for (int i = front; i < front+size(); i++) {
                System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
            }
        }

    }

    /**
     * 显示队列的头部数据
     *
     * @return
     */
    public int peekQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空-----");
        }
        return arr[front];
    }

}
